package cn.good.yan.service.t3;

import cn.good.yan.service.t2.mapper.UserMapper;
import cn.good.yan.service.t2.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 3. hyperloglog  统计
 *
 * @author shengren.yan
 * @create 2023-11-12
 */
@Service
@Slf4j
public class HyperloglogService {

    @Resource
    private RedisTemplate redisTemplate;

    // 去重
    public static void main(String[] args) {
        // HashSet 去重
        List<String> list1 = Arrays.asList("127.0.1", "127.0.2", "127.0.3", "127.0.1");
        HashSet<String> strings = new HashSet<>(list1);
        System.out.println(strings);
        // hyperloglog 基数统计

    }

    /**
     * 模拟，初始化，就加载 key为hll，添加不同的ip地址
     */
//    @PostConstruct  // 初始化就会加载 init方法
    public void init(){
        new Thread(()->{
            String ip = null;
            for (int i = 0; i < 200; i++) {
                Random random = new Random();
                ip = random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256);
                // 进行保存 到Redis中
                Long hll = redisTemplate.opsForHyperLogLog().add("hll", ip);
                log.info("ip = {}, 该IP地址访问首页的次数={}",ip,hll);
                try {
                    // 暂停3秒钟
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    /**
     * 访问 redis中 hyperloglog 的key hll
     * @return long
     */
    public long uv() {
        return redisTemplate.opsForHyperLogLog().size("hll");
    }

}
